import { buildLastMessage, buildLastMessageTime, clearUnReadMessage, getUserInfo } from '@/net/send-message'

import { nextTick } from '@vue/composition-api'
import store from '@/store/index'
import { ding, sortedUser } from '@/utils/system-util'
import msg from '@/plugins/msg'
import { scrollToView } from '@/utils/dom'

export default {
  COMMAND_LOGIN_RESP: (state) => {
    getUserInfo(state.currentUserId)
  },
  // 编辑用户信息返回
  COMMAND_EDIT_PROFILE_REST: (state, data) => {
    const { user } = data.data
    store.commit('setCurUser', user)
  },
  // 获取用户信息响应
  COMMAND_GET_USER_RESP: (state, data) => {
    const { groups, user } = data.data
    store.commit('setCurUser', { ...user })
    groups.forEach(x => {
      x.lastMessage = buildLastMessageTime(x.lastMessage)
    })
    state.loadedRooms = [...groups]
    nextTick(() => {
      store.commit('setLoadingRooms', false)
      store.commit('setRoomsLoaded', true)
    })
    // 获取历史消息
    if (state.loadedRooms.length > 0) {
      store.commit('changeRoom', state.loadedRooms[0].roomId)
    }
  },

  // 用户配置响应
  COMMAND_USER_GROUP_CONFIG_RESP: (state, data) => {
    const { data: config } = data

    const index = state.loadedRooms.findIndex(r => r.roomId === config.roomId)
    if (index === -1) {
      return
    }
    switch (config.type) {
      case 'NOTICE':
        state.loadedRooms[index].notice = config.notice
        break
      case 'MOVE_TOP':
        state.loadedRooms[index].index = config.index
        break
      case 'BLACK':
        state.loadedRooms[index].black = config.black
        break
    }

    state.loadedRooms = [...state.loadedRooms]
  },

  // 获取历史消息响应
  COMMAND_GET_MESSAGE_RESP: (state, data) => {
    const { type, messages: loadMessages, returnDefault, groupAnnouncementRead, messageId, roomId } = data.data
    // 判断是不是请求默认的消息, 即点击了达到底部的图标, 如果是,则清空所有的消息,设定搜索模式为结束
    if (returnDefault) {
      store.commit('clearMessages')
      store.commit('setMessageLoaded', false)
      store.commit('setCacheMessageLoaded', false)
      store.commit('setNewMessageLoaded', true)
      store.commit('setCacheNewMessageLoaded', true)
    }

    if (loadMessages.length < 20) {
      if (type === 'DOWN') {
        store.commit('setNewMessageLoaded', true)
        store.commit('setCacheNewMessageLoaded', true)
      } else {
        store.commit('setCacheMessageLoaded', true)
      }
    }

    store.commit('assimilateMessages', { loadMessages, type, messageId, roomId })

    if (!groupAnnouncementRead) {
      msg.$emit('SHOW_ANNOUNCEMENT')
    }
  },

  // 聊天请求
  COMMAND_CHAT_RESP: (state, data) => {
    const message = data.data
    if (message.receiver && message.receiver !== state.currentUserId) return

    const roomIndex = state.loadedRooms.findIndex(r => message.roomId === r.roomId)

    if (state.loadedRooms[roomIndex].notice && message.senderId !== state.curUser._id) {
      ding()
    }

    // 设置最后一条消息
    const lastMessage = buildLastMessage(message)
    state.loadedRooms[roomIndex] = { ...state.loadedRooms[roomIndex], lastMessage }
    // 将目标消息置顶
    store.commit('upRoom', message.roomId)
    if (message.roomId === state.roomId) {
      clearUnReadMessage(state.roomId)
      store.commit('pushMessage', message)
      // 检查等待发送列表
      store.commit('removeWaitSendMessage', message._id)
    } else {
      state.loadedRooms[roomIndex].unreadCount = message.unreadCount
    }
    state.loadedRooms = [...state.loadedRooms]
    console.log(state.loadedRooms[roomIndex])
    if (process.env.IS_ELECTRON) {
      const room = state.loadedRooms[roomIndex]
      window.require('electron').ipcRenderer.send('notify-list', {
        roomId: room.roomId,
        roomName: room.roomName,
        unreadCount: room.unreadCount,
        avatar: room.avatar
      })
    }
  },

  // 用户状态变化消息
  COMMAND_USER_STATUS_RESP: (state, data) => {
    const { roomId, user } = data.data

    const roomIndex = state.loadedRooms.findIndex(r => r.roomId === roomId)
    if (roomIndex === -1) return

    if (state.loadedRooms[roomIndex].friendId === user._id) {
      state.loadedRooms[roomIndex].avatar = user.avatar
      state.loadedRooms[roomIndex].roomName = user.username
    }

    const userIndex = state.loadedRooms[roomIndex].users.findIndex(r => r._id === user._id)
    if (userIndex !== -1) {
      state.loadedRooms[roomIndex].users[userIndex] = user
      // state.loadedRooms[roomIndex].users = [...state.loadedRooms[roomIndex].users]
      state.loadedRooms[roomIndex].users = sortedUser(state.loadedRooms[roomIndex].users)
    }
    state.loadedRooms = [...state.loadedRooms]
  },

  // 加入群组返回
  COMMAND_JOIN_GROUP_NOTIFY_RESP: (state, data) => {
    const room = data.data
    const index = state.loadedRooms.findIndex(r => r.roomId === room.roomId)
    if (index === -1) {
      state.loadedRooms.push(room)
      state.loadedRooms = [...state.loadedRooms]
    } else {
      state.loadedRooms[index].users = [...room.users]
      state.loadedRooms[index].users = sortedUser(state.loadedRooms[index].users)
      state.loadedRooms = [...state.loadedRooms]
    }
    setTimeout(() => {
      store.commit('setLoadingRooms', false)
      store.commit('setRoomsLoaded', true)
    })

    if (state.loadedRooms.length === 1) {
      store.commit('changeRoom', room.roomId)
    }

    const newIndex = state.loadedRooms.findIndex(r => r.roomId === room.roomId)
    // 如果加入的用户里包含创建者，那么切换位置
    const userIndex = state.loadedRooms[newIndex].users.findIndex(r => r._id === state.currentUserId)
    if (userIndex !== -1) {
      if (state.loadedRooms[newIndex].users[userIndex].role === 'CREATE' || state.loadedRooms[newIndex].users[userIndex].role === 'ADMIN') {
        store.commit('changeRoom', room.roomId)
      }
    }
  },

  // 表情回复
  COMMAND_SEND_MESSAGE_REACTION_RESP: (state, data) => {
    const reaction = data.data
    if (state.roomId !== reaction.roomId) {
      return
    }
    const cacheMessageIndex = state.cacheMessages.findIndex(r => reaction.messageId === r._id)
    if (cacheMessageIndex === -1) {
      return
    }
    if (state.cacheMessages[cacheMessageIndex].reactions) {
      state.cacheMessages[cacheMessageIndex].reactions = reaction.reactions
    } else {
      state.cacheMessages[cacheMessageIndex] = {
        ...state.cacheMessages[cacheMessageIndex],
        reactions: reaction.reactions
      }
    }
    state.cacheMessages = [...state.cacheMessages]

    const messageIndex = state.messages.findIndex(r => reaction.messageId === r._id)
    if (messageIndex === -1) {
      return
    }
    if (state.messages[messageIndex].reactions) {
      state.messages[messageIndex].reactions = reaction.reactions
    } else {
      state.messages[messageIndex] = { ...state.messages[messageIndex], reactions: reaction.reactions }
    }
    state.messages = [...state.messages]
  },

  // 群组用户移除返回
  COMMAND_REMOVE_GROUP_USER_RESP: (state, data) => {
    const { userId, roomId: serveRoomId } = data.data
    const index = state.loadedRooms.findIndex(r => r.roomId === serveRoomId)
    if (userId === state.currentUserId) {
      state.loadedRooms.splice(index, 1)
      state.loadedRooms = [...state.loadedRooms]
      if (serveRoomId === state.roomId) {
        if (state.loadedRooms.length > 0) {
          store.commit('changeRoom', state.loadedRooms[0].roomId)
        }
      }

      return
    }
    const userIndex = state.loadedRooms[index].users.findIndex(r => r._id === userId)
    state.loadedRooms[index].users.splice(userIndex, 1)

    state.loadedRooms = [...state.loadedRooms]
  },

  // 解散群聊响应
  COMMAND_DISBAND_GROUP_RESP: (state, data) => {
    const { roomId: disbandRoomId } = data.data
    const index = state.loadedRooms.findIndex(r => r.roomId === disbandRoomId)
    state.loadedRooms.splice(index, 1)
    state.loadedRooms = [...state.loadedRooms]

    if (disbandRoomId === state.roomId) {
      store.commit('changeRoom', state.loadedRooms[0]?.roomId)
    }
  },

  // 移交群主响应
  COMMAND_HANDOVER_GROUP_RESP: (state, data) => {
    const { roomId, oldAdmin, newAdmin } = data.data
    const index = state.loadedRooms.findIndex(r => r.roomId === roomId)

    const oldAdminIndex = state.loadedRooms[index].users.findIndex(r => r._id === oldAdmin)
    state.loadedRooms[index].users[oldAdminIndex].role = 'GENERAL'

    const newAdminIndex = state.loadedRooms[index].users.findIndex(r => r._id === newAdmin)
    state.loadedRooms[index].users[newAdminIndex].role = 'ADMIN'

    state.loadedRooms[index].users = sortedUser(state.loadedRooms[index].users)
    state.loadedRooms = [...state.loadedRooms]
  },

  // 修改群组信息响应
  COMMAND_EDIT_GROUP_PROFILE_RESP: (state, data) => {
    const { roomId: changeRoomId, roomName, avatar } = data.data
    const index = state.loadedRooms.findIndex(r => r.roomId === changeRoomId)
    if (roomName) {
      state.loadedRooms[index].roomName = roomName
    }
    if (avatar) {
      state.loadedRooms[index].avatar = avatar
    }
    state.loadedRooms = [...state.loadedRooms]
  },

  // 设置群公开响应
  COMMAND_SET_PUBLIC_ROOM_RESP: (state, data) => {
    const { roomId: changeRoomId, publicRoom } = data.data
    const index = state.loadedRooms.findIndex(r => r.roomId === changeRoomId)
    state.loadedRooms[index] = {
      ...state.loadedRooms[index],
      publicRoom
    }

    state.loadedRooms = [...state.loadedRooms]
  },

  // 删除群组信息响应
  COMMAND_MESSAGE_DELETE_RESP: (state, data) => {
    const { _id, roomId: messageRoomId, isLastMessage } = data.data
    if (messageRoomId === state.roomId) {
      const index = state.messages.findIndex(r => r._id === _id)
      if (index !== -1) {
        state.messages[index].deleted = true
        state.messages = [...state.messages]
      }
      if (isLastMessage) {
        const lastMessage = buildLastMessage(data.data)
        const roomIndex = state.loadedRooms.findIndex(r => r.roomId === messageRoomId)
        state.loadedRooms[roomIndex].lastMessage = lastMessage
        state.loadedRooms = [...state.loadedRooms]
      }
    }
  },

  // 系统会话创建响应
  COMMAND_SYSTEM_MESSAGE_RESP: (state, data) => {
    const room = data.data.group
    const users = data.data.users
    const index = state.loadedRooms.findIndex(r => r.roomId === room.roomId)
    if (index === -1) {
      room.users = users
      state.loadedRooms[state.loadedRooms.length] = room
      state.loadedRooms = [...state.loadedRooms]
    }
    if (state.loadedRooms.length === 1) {
      store.commit('changeRoom', room.roomId)
    }
  },

  // 已读消息响应
  COMMAND_MESSAGE_READ_RESP: (state, data) => {
    const { roomId: messageRoomId, messageId } = data.data

    if (messageRoomId === state.roomId) {
      const index = state.messages.findIndex(r => r._id === messageId)
      if (index !== -1) {
        state.messages[index].seen = true
        state.messages = [...state.messages]
      }
    }

    const index = state.loadedRooms.findIndex(r => r.roomId === messageRoomId)
    if (state.loadedRooms[index].lastMessage.messageId === messageId) {
      state.loadedRooms[index].lastMessage.seen = true
      state.loadedRooms = [...state.loadedRooms]
    }
  },

  // 自己的表情包返回
  COMMAND_EMOTICON_RESP: (state, data) => {
    data.data.forEach(x => {
      const index = state.userEmoticons.findIndex(r => r._id === x._id)
      if (index === -1) {
        state.userEmoticons.push(x)
      }
    })
    state.userEmoticonLoaded = data.data < 20
  },

  COMMAND_EMOTICON_OPERATION_RESP: (state, data) => {
    const { type, emoticon } = data.data
    switch (type) {
      case 'INSERT_EMOTICON_TO_USER':
        if (state.userEmoticons.findIndex(r => r._id === emoticon._id) === -1) {
          state.userEmoticons.unshift(emoticon)
        }
        break
      case 'INSERT_TO_USER':
        if (state.userEmoticons.findIndex(r => r._id === emoticon._id) === -1) {
          state.userEmoticons.unshift(emoticon)
        }
        msg.$emit('INSERT_TO_USER_MSG', data)
        break
      case 'DELETE':
        state.userEmoticons.splice(state.userEmoticons.findIndex(r => r._id === emoticon._id), 1)
        msg.$emit('EMOTICON_DELETE_MSG', data)
        break
      case 'MOVE_TOP':
        state.userEmoticons.splice(state.userEmoticons.findIndex(r => r._id === emoticon._id), 1)
        state.userEmoticons.unshift(emoticon)
        msg.$emit('EMOTICON_MOVE_TOP', data)
        break
      case 'INSERT_TO_STORE':
        if (state.emoticons.findIndex(r => r._id === emoticon._id)) {
          state.emoticons.splice(state.emoticons.findIndex(r => r._id === emoticon._id), 1)
        }
        state.emoticons.unshift(emoticon)
        msg.$emit('EMOTICON_INSERT_TO_STORE', data)
        break
    }
  },

  COMMAND_GROUP_ANNOUNCEMENT_RESP: (state, data) => {
    const announcement = data.data
    const index = state.loadedRooms.findIndex(r => r.roomId === announcement.roomId)
    state.loadedRooms[index] = {
      ...state.loadedRooms[index],
      announcement
    }
    state.loadedRooms = [...state.loadedRooms]
    if (state.loadedRooms[index].roomId === state.roomId) {
      msg.$emit('SHOW_ANNOUNCEMENT', announcement)
    }
  },

  COMMAND_SEARCH_MESSAGE_PAGE_RESP: (state, data) => {
    const { messages, messageId } = data.data
    state.cacheMessages = [...messages]
    state.messages = [...messages]
    store.commit('setNewMessageLoaded', false)
    store.commit('setMessageLoaded', false)
    store.commit('setCacheNewMessageLoaded', false)
    store.commit('setCacheMessageLoaded', false)
    const element = document.getElementById(messageId)
    if (!element) {
      setTimeout(() => {
        const element = document.getElementById(messageId)
        scrollToView(element)
      }, 1000)
    }
  }

}
